<?php

namespace api\modules\v1\forms\rbac;

use Yii;
use yii\base\Model;
use common\models\member\Member;
use common\models\rbac\Action;
use common\models\rbac\Menu;
use common\models\rbac\Module;
use common\models\rbac\RolePermission;

/**
 * 模块
 *
 * Class ModuleForm
 * @package api\modules\v1\forms\rbac
 */
class ModuleForm extends Model
{
    /**
     * 模块ID
     *
     * @var
     */
    public $id;

    /**
     * 模块名称
     *
     * @var
     */
    public $name;

    /**
     * 模块链接
     *
     * @var
     */
    public $url;

    /**
     * 模块ico
     *
     * @var
     */
    public $class_style;


    /**
     * 排序
     *
     * @var
     */
    public $sort;

    /**
     * 状态
     *
     * @var
     */
    public $status;

    /**
     * 用户ID
     *
     * @var
     */
    public $member_id;

    // 模块信息
    protected $_module;


    public function rules()
    {
        return [
            // 参数验证
            [['member_id', 'name', 'url', 'class_style', 'status'], 'required', 'message' => '{attribute}不能为空', 'on' => ['create']],
            [['member_id', 'id', 'name', 'url', 'class_style', 'status'], 'required', 'message' => '{attribute}不能为空', 'on' => ['edit']],
            [['member_id', 'id'], 'required', 'message' => '{attribute}不能为空', 'on' => ['delete']],

            [['member_id'], 'checkMemberId', 'skipOnEmpty' => false, 'on' => ['create', 'edit', 'delete']],
            [['id'], 'checkModule', 'skipOnEmpty' => false, 'on' => ['edit', 'delete']],
            [['name'], 'checkName', 'skipOnEmpty' => false, 'on' => ['create', 'edit']],
            [['url'], 'checkUrl', 'skipOnEmpty' => false, 'on' => ['create', 'edit']],
            [['class_style'], 'checkClassStyle', 'skipOnEmpty' => false, 'on' => ['create', 'edit']],
            [['sort'], 'checkSort', 'skipOnEmpty' => true, 'on' => ['create', 'edit']],
            [['status'], 'checkStatus', 'skipOnEmpty' => false, 'on' => ['create', 'edit']],
        ];
    }

    public function scenarios()
    {
        $scenarios = parent::scenarios();

        // 新增
        $scenarios['create'] = ['member_id', 'name', 'url', 'class_style', 'sort', 'status'];

        // 编辑
        $scenarios['edit'] = ['member_id', 'id', 'name', 'url', 'class_style', 'sort', 'status'];

        // 删除
        $scenarios['delete'] = ['member_id', 'id'];

        return $scenarios;
    }

    /**
     * @return array
     */
    public function attributeLabels()
    {
        return [
            'member_id' => '用户ID',
            'id' => '模块ID',
            'name' => '模块名称',
            'url' => '模块链接',
            'class_style' => '模块icon',
            'sort' => '排序',
            'status' => '状态',
        ];
    }

    /**
     * 检验用户UID
     *
     * @param $attribute
     * @return bool
     */
    public function checkMemberId($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $member = Yii::$app->services->member->getInfo(['id' => $this->member_id]);
        if ($member['is_super'] != Member::IS_SUPER_YES) {
            $this->addError($attribute, '非超管，无权限操作');
            return true;
        }
    }

    /**
     * 检验模块信息
     *
     * @param $attribute
     * @return bool
     */
    public function checkModule($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $module = $this->getModule();
        if (empty($module)) {
            $this->addError($attribute, '模块不存在');
            return true;
        }

        if ($module->status == Module::STATUS_DELETE) {
            $this->addError($attribute, '模块已删除，无法操作');
            return true;
        }

        if (($this->getScenario() == 'edit' && $this->status == Module::STATUS_INVALID)
            || $this->getScenario() == 'delete') {
            $rolePermission = Yii::$app->services->rolePermission->findInfo([
                'permission_id' => $this->id,
                'permission_type' => RolePermission::PERMISSION_TYPE_MODULE,
            ]);
            if ($rolePermission) {
                $this->addError($attribute, "模块存在绑定角色");
                return true;
            }

            $menu = Menu::findOne([
                'module_id' => $this->id,
                'status' => Menu::STATUS_ENABLE,
            ]);
            if ($menu) {
                $this->addError($attribute, "模块存在绑定菜单");
                return true;
            }

            $action = Action::findOne([
                'module_id' => $this->id,
                'status' => Action::STATUS_ENABLE,
            ]);
            if ($action) {
                $this->addError($attribute, "模块存在绑定动作");
                return true;
            }
        }
    }

    /**
     * 校验菜单名称
     *
     * @param $attribute
     */
    public function checkName($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $len = mb_strlen($this->name);
        if ($len > 10) {
            $this->addError($attribute, '菜单名称过长，最多10个字');
            return true;
        }

        // 是否检验
        $isCheck = true;
        if ($this->getScenario() == 'edit') {
            $module = $this->getModule();
            // 菜单参数未改变【跳过】
            if ($module->name == $this->name) {
                $isCheck = false;
            }
        }

        if ($isCheck) {
            $moduleInfo = Module::findOne([
                'name' => $this->name,
                'status' => [Module::STATUS_INVALID, Module::STATUS_ENABLE],
            ]);

            if ($moduleInfo) {
                $this->addError($attribute, "模块【{$this->name}】已存在");
                return true;
            }
        }
    }

    /**
     * 校验菜单url
     *
     * @param $attribute
     */
    public function checkUrl($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $len = strlen($this->url);
        if ($len > 80) {
            $this->addError($attribute, '模块链接过长，最多80个字节');
            return true;
        }
    }

    /**
     * 校验模块icon
     *
     * @param $attribute
     */
    public function checkClassStyle($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $len = strlen($this->class_style);
        if ($len > 50) {
            $this->addError($attribute, '模块icon过长，最多50个字节');
            return true;
        }
    }

    /**
     * 校验排序
     *
     * @param $attribute
     */
    public function checkSort($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        if ($this->sort < 0) {
            $this->addError($attribute, '排序值不能小于0');
            return true;
        }
    }

    /**
     * 校验模块状态
     *
     * @param $attribute
     */
    public function checkStatus($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        if (!in_array($this->status, [Module::STATUS_INVALID, Module::STATUS_ENABLE])) {
            $this->addError($attribute, "非法状态");
            return true;
        }
    }

    /**
     * 获取模块信息
     *
     * @return Module|null
     */
    public function getModule()
    {
        if (empty($this->_module)) {
            $this->_module = Module::findOne($this->id);
        }

        return $this->_module;
    }
}
